<template>
    <el-form-item
        :label="`会员${obtainText}权限`"
        prop="participation_rules"
        :inline-message="true"
        :required="showCheck"
    >
        <el-switch v-model="ruleForm.participation_rules" :active-value="1" :inactive-value="0" @change="switchParticipationRules"/>
    </el-form-item>

    <div v-if="showCheck">
        <el-form-item>
            <el-checkbox v-model="ruleForm.levelIdsChecked" @change="checkChangeLevel">
                <span class="mr8">指定可{{ obtainText }}的会员等级</span>
            </el-checkbox>
            <el-form-item v-if="ruleForm.levelIdsChecked" prop="levelIds">
                <el-select-v2
                    v-model="ruleForm.levelIds"
                    :props="{ value: 'id', label: 'name' }"
                    :options="levelOptions"
                    placeholder="请选择会员等级"
                    class="w200"
                    multiple
                    clearable
                    collapse-tags
                    collapse-tags-tooltip
                />
            </el-form-item>
        </el-form-item>
        <el-form-item prop="crowdTypeChecked" :class="{ mb8: ruleForm.crowdTypeChecked || isPaidMember }">
            <el-checkbox v-model="ruleForm.crowdTypeChecked" @change="checkChangeCrowdType">指定不可{{ obtainText }}的人群</el-checkbox>
        </el-form-item>
        <div v-if="ruleForm.crowdTypeChecked" class="pl20">
            <el-form-item prop="crowdType" class="mb8">
                <el-radio-group v-model="ruleForm.crowdType" @change="radioChangeCrowdType">
                    <el-radio :value="2">上传人群包</el-radio>
                    <el-radio :value="1">自定义人群包</el-radio>
                </el-radio-group>
            </el-form-item>
            <el-form-item prop="denyGroups">
                <!--上传人群包-->
                <div v-if="ruleForm.crowdType === 2">
                    <div v-if="ruleForm.denyGroups.id" class="upload-deny-groups">
                        <el-tooltip placement="top">
                            <span class="ellipsis1" style="max-width: 270px;">{{ ruleForm.denyGroups.name || ruleForm.denyGroups.filename }}</span>
                            <template #content>
                                <span>{{ ruleForm.denyGroups.name || ruleForm.denyGroups.filename }}</span>
                            </template>
                        </el-tooltip>
                        <span class="ph10">|</span>
                        <span class="text-nowrap">{{ ruleForm.denyGroups.count }}人</span>
                        <el-button link class="ml12" type="primary" :icon="Switch" :loading="denyGroupsLoading" @click="onUploadMemberImport"/>
                        <el-icon :size="16" class="pointer ml12 danger-color" @click="resetDenyGroups">
                            <CircleClose/>
                        </el-icon>
                    </div>
                    <el-button v-else class="mr8" type="primary" :loading="denyGroupsLoading" @click="onUploadMemberImport">上传人群包</el-button>
                    <el-text class="form-tip-color">文件大小不超过10M</el-text>
                    <el-text type="primary" tag="ins" class="fz12 pointer pl8" @click="downloadMemberImport">点击下载「上传人群包模板」</el-text>

                    <UploadFile
                        style="display: none;"
                        @change="uploadActionMemberImport"
                        file-accept="xls,xlsx"
                        accept="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet,application/vnd.ms-excel"
                    >
                        <span ref="uploadMemberImportRef"/>
                    </UploadFile>
                </div>
                <!--自定义人群包-->
                <div v-if="ruleForm.crowdType === 1">
                    <el-select-v2
                        v-model="ruleForm.denyGroups.id"
                        :props="{ value: 'id', label: 'name' }"
                        :options="memberGroupOptions"
                        placeholder="请选择人群包"
                        class="w200"
                        clearable
                        filterable
                        @change="onChange"
                    />
                    <el-text type="primary" class="ml12 fz12" tag="ins" pointer @click="newMemberGroups">去新建人群包</el-text>
                </div>
            </el-form-item>
        </div>
    </div>
</template>

<script setup lang="ts">
    import { ref, toRefs, computed, onUnmounted, onMounted } from "vue";
    import { ElMessage } from "element-plus";
    import { CircleClose, Switch } from "@element-plus/icons-vue";
    import { useRouter } from "vue-router";
    import { _mallStore } from "@/store/config";
    import UploadFile from "@/components/form/UploadFile.vue";
    import { postRestfulMallGrantMembersImport } from "@/assets/api";
    import { resetBuyLimit } from "@/components/formUtils/BuyLimit";

    const router = useRouter();

    const props = defineProps({
        obtainText: {
            type: String,
            default: '购买',
        },
        ruleForm: {
            type: Object,
            default: () => {
                return {}
            }
        },
        levelOptions: {
            type: Array,
            default: () => {
                return []
            }
        },
        memberGroupOptions: {
            type: Array,
            default: () => {
                return []
            }
        }
    });

    onUnmounted(() => {
        document.removeEventListener('visibilitychange', visibilityChange);
    });
    onMounted(() => {
        document.addEventListener('visibilitychange', visibilityChange);
    })

    const emit = defineEmits(['update-member', 'change']);
    const { isPaidMember } = toRefs(_mallStore);// 付费会员商场
    const { ruleForm }: ObjValueAny = props;
    const showCheck = computed(() => {
        return ruleForm.participation_rules === 1;
    })
    // 会员领取权限 =============================================
    // 新建人群包
    let routerNewMemberGroups = false;// 去新建人群包
    const newMemberGroups = () => {
        routerNewMemberGroups = true;
        const { href } = router.resolve({
            path: '/coupon',
        })
        window.open(href, '_blank');
    }
    // 离开当前tab标签 新建人群包
    const visibilityChange = () => {
        if (document.visibilityState === 'hidden') {
            // 离开
            // console.log('那我走？我走了啊？我可真走了。。');
        } else {
            // 回来
            if (routerNewMemberGroups) {
                routerNewMemberGroups = false;
                emit('update-member');
            }
        }
    }
    // 会员领取权限开关 =============================================
    const switchParticipationRules = () => {
        resetBuyLimit(ruleForm);
    }
    // 指定可参与的会员等级 复选框
    const checkChangeLevel = () => {
        clearLevelIds();
    }
    // 清空 指定可参与的会员等级
    const clearLevelIds = () => {
        ruleForm.levelIds = [];
        onChange();
    }
    // 指定不可领取的人群 复选
    const checkChangeCrowdType = () => {
        ruleForm.crowdType = 2;
        radioChangeCrowdType();
    }
    // 指定不可领取的人群 选择
    const radioChangeCrowdType = () => {
        resetDenyGroups();
    }
    // 清空 指定不可领取的人群
    const resetDenyGroups = () => {
        ruleForm.denyGroups = { id: '', count: 0, name: '' };
        onChange();
    }
    // 点击 上传人群包按钮
    const uploadMemberImportRef = ref();
    const onUploadMemberImport = () => {
        uploadMemberImportRef.value.click();
    }
    // 上传人群包
    const denyGroupsLoading = ref<boolean>(false);
    const uploadActionMemberImport = async (raw: File) => {
        denyGroupsLoading.value = true;
        const files = new FormData();
        files.append('file', raw);
        files.append('limit', (10 * 1024 * 1024).toString());
        postRestfulMallGrantMembersImport(files).then((resp: ObjValueAny) => {
            if (resp.code === 200) {
                const { data } = resp;
                ruleForm.denyGroups = {
                    id: data.member_group_id,
                    filename: raw.name,
                    count: data.grant_members_count,
                }
            } else {
                ElMessage.error(resp.msg);
            }
            onChange();
        }).finally(() => {
            denyGroupsLoading.value = false;
        })
    }
    // 下载人群包模板
    const downloadMemberImport = () => {
        const createA = document.createElement('a');
        createA.href = '/static/files/上传人群包模板.xlsx';
        createA.click();
    }

    const onChange = () => {
        emit('change');
    }

    defineExpose({
        switchParticipationRules
    })

</script>

<style scoped lang="scss">
    /* 会员等级*/
    .level-ids__error :deep(.el-form-item__error) {
        left: 148px;
    }

    /* 指定不可领取的人群*/
    .upload-deny-groups {
        display: flex;
        align-items: center;
        box-sizing: border-box;
        box-shadow: 0 0 0 1px var(--el-input-border-color, var(--el-border-color)) inset;
        border-radius: var(--el-border-radius-base);
        width: fit-content;
        padding: 2px 12px;
        color: var(--el-text-color-regular);
    }
</style>